package com.abhimanyu.dataaccess;

import java.util.ArrayList;
import java.util.List;

import com.abhimanyu.dataaccess.model.User;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;

/**
 * @author Abhimanyu
 *
 */
public class GoogleDatastoreUsersDao extends AbstractUsersDao {

	@Override
	public List<User> fetchAll() {
		List<User> listOfUsers = null;
		User user = null;
		Filter queryFilter = new FilterPredicate(getEnabledColumnName(),
				FilterOperator.EQUAL, true);
		Query query = new Query(getTableName()).setFilter(queryFilter);
		PreparedQuery preparedQuery = getDatastoreService().prepare(query);

		for (Entity userEntity : preparedQuery.asIterable()) {
			if (listOfUsers == null) {
				listOfUsers = new ArrayList<User>();
			}

			user = constructUser(userEntity);
			listOfUsers.add(user);
		}
		return listOfUsers;
	}

	public Iterable<Entity> executeFetchAllUsers() {
		Filter queryFilter = new FilterPredicate(getEnabledColumnName(),
				FilterOperator.EQUAL, true);
		Query query = new Query(getTableName()).setFilter(queryFilter);
		PreparedQuery preparedQuery = getDatastoreService().prepare(query);
		return preparedQuery.asQueryResultIterable();
	}

	@Override
	public void save(User user) {

		Entity userEntity = new Entity(getTableName());
		userEntity.setProperty(getUserNameColumnName(), user.getUserName());
		userEntity.setProperty(getEmailAddressColumnName(), user.getEmail());
		userEntity.setProperty(getMobileNumberColumnName(),
				user.getMobileNumber());
		userEntity.setProperty(getEnabledColumnName(), user.isEnabled());
		userEntity.setProperty(getScheduledAtColumnName(),
				user.getScheduledAt());
		getDatastoreService().put(userEntity);
	}

	public User constructUser(Entity userEntity) {
		User user = new User();
		if (userEntity.hasProperty(getUserNameColumnName()))
			user.setUserName((String) userEntity
					.getProperty(getUserNameColumnName()));

		if (userEntity.hasProperty(getEmailAddressColumnName()))
			user.setEmail((String) userEntity
					.getProperty(getEmailAddressColumnName()));

		if (userEntity.hasProperty(getEnabledColumnName()))
			user.setEnabled((Boolean) userEntity
					.getProperty(getEnabledColumnName()));

		if (userEntity.hasProperty(getMobileNumberColumnName()))
			user.setMobileNumber((String) userEntity
					.getProperty(getMobileNumberColumnName()));

		if (userEntity.hasProperty(getScheduledAtColumnName()))
			user.setScheduledAt((String) userEntity
					.getProperty(getScheduledAtColumnName()));

		return user;
	}

	public void update(User object) {
		// TODO Auto-generated method stub
		
	}	
	
}
